/**
 * 对评论点赞
 */

const { db, query } = require("../../db/db");
const util = require("util");
const moment = require("moment");

async function PostLike(req, res) {
  const CreateUserId = Number(req.params.username);
  const CommentId = req.body.CommentId || null;

  console.log("3333333", CreateUserId, CommentId);

  //查看用户是否点赞
  const select_user_like_info = util.format(
    "Select * from Comment_Like_Info where UserId=%s",
    CreateUserId
  );

  const select_user_like_info_res = await query(select_user_like_info);

  if (select_user_like_info_res[0]) {
    //已点过赞 执行取消操作
    const delete_user_like_info = util.format(
      "Delete From Comment_Like_Info Where CommentId=%s AND UserId=%s",
      CommentId,
      CreateUserId
    );
    await query(delete_user_like_info);
    const sql_comment_LikeNum = util.format(
      "Select LikeNum From Comment where CommentId=%s",
      CommentId
    );

    const sql_comment_LikeNum_res = await query(sql_comment_LikeNum);

    if (sql_comment_LikeNum_res[0]) {
      var LikeNum = sql_comment_LikeNum_res[0].LikeNum;
      LikeNum--;

      const Update_comment = util.format(
        "Update Comment set LikeNum=%s where CommentId=%s",
        LikeNum,
        CommentId
      );

      await query(Update_comment);
    }
  } else {
    //未点赞
    const insert_user_like_info = util.format(
      "Insert Into Comment_Like_Info (CommentId,UserId) values (%s,%s)",
      CommentId,
      CreateUserId
    );

    await query(insert_user_like_info);
    const sql_comment_LikeNum = util.format(
      "Select LikeNum From Comment where CommentId=%s",
      CommentId
    );

    const sql_comment_LikeNum_res = await query(sql_comment_LikeNum);

    if (sql_comment_LikeNum_res[0]) {
      var LikeNum = sql_comment_LikeNum_res[0].LikeNum;
      LikeNum++;
      console.log("执行增加", LikeNum);

      const Update_comment = util.format(
        "Update Comment set LikeNum=%s where CommentId=%s",
        LikeNum,
        CommentId
      );

      await query(Update_comment);
    }
  }

  res.send({
    status: 0,
  });
}

module.exports = { PostLike };
